package sicnu.cs.ich.security.util;

import org.springframework.security.core.GrantedAuthority;
import sicnu.cs.ich.security.domain.entity.Permission;

import java.util.*;
import java.util.stream.Collectors;

public class CollectionUtil {
    public static TreeSet<? extends GrantedAuthority> toTreeSet(Collection<? extends GrantedAuthority> authorities) {
        return authorities.stream().collect(
                Collectors.toCollection(
                        () -> new TreeSet<>(
                                Comparator.comparing(GrantedAuthority::getAuthority)
                        )
                )
        );
    }

    public static List<?> convertObjectToList(Object obj) {
        List<?> list = new ArrayList<>();
        if (obj.getClass().isArray()) {
            list = Arrays.asList((Object[]) obj);
        } else if (obj instanceof Collection) {
            list = new ArrayList<>((Collection<?>) obj);
        }
        return list;
    }

    public static List<Permission> permissionToMenu(List<Permission> permissions) {
        return permissionToTree(permissions.stream().filter(Permission::isMenu).collect(Collectors.toList()));
    }

    public static List<Permission> permissionToTree(List<Permission> permissions) {
        Map<Integer,Permission> map = new HashMap<>();
        for (Permission vo : permissions) {
            var parent = map.get(vo.getParentId());
            if (parent!=null){
                parent.addChild(vo);
            }
            map.put(vo.getId(),vo);
        }
        List<Permission> menu = new ArrayList<>();
        map.forEach((k,v)->{
            if(!map.containsKey(v.getParentId())){
                menu.add(v);
            }
        });
        return menu;
    }

    public static boolean isEmpty(List<?> list) {
        return list == null || list.size() == 0;
    }
}
